import { Message } from 'element-ui'
import axios from 'axios';
import my_sale_deals from "@/components/pages/Deal/sort/my_sale_deals";

var url = 'ws://www.caihuay.com.cn:2348'
var ws;
var tt;
var lockReconnect = false;//避免重复连接
// var clientId = window.sessionStorage.getItem("token")//用户token

var websocket = {
    Init: function() {
        if ("WebSocket" in window) {

            if(window.ws)
            {
                lockReconnect = true;//避免重复连接
                window.ws.close()
            }

            lockReconnect = false;//避免重复连接
            window.ws = new WebSocket(url); // 全站注册
            // console.log(window.ws);
        }
        else {
            console.log("您的浏览器不支持 WebSocket!");
            return;
        }

        window.ws.onmessage = function(e) {
            console.log("接收消息:" + e.data)
            // heartCheck.start()
            // if(e.data=='ok'){//心跳消息不做处理
            //     return
            // }
            messageHandle(e.data)
        }

        window.ws.onclose = function() {
            console.log("连接已关闭")
            // Message({
            //     message: '连接已关闭',
            //     type: 'error',
            // });
            reconnect();
        }

        window.ws.onopen = function() {
            console.log("连接成功");
            // Message({
            //     message: '连接成功',
            //     type: 'success',
            // });
            // heartCheck.start();
        }

        window.ws.onerror = function() {
            console.log("服务器/本地网络有问题");


            if (navigator.onLine) // 本地有网
            {
                Message({
                    message: '正在连接服务器',
                });
                reconnect()
            }
            else
            {
                Message({
                    message: '本地无网络连接，请检查后刷新',
                    type: 'error',
                });
                lockReconnect = true;
                window.ws.close()
            }


        }
    },
    Send:function(sender,reception,body,flag){
        let data = {
            sender:sender,
            reception:reception,
            body:body,
            flag:flag
        }
        let msg= JSON.stringify(data)
        console.log("发送消息："+msg)
        window.ws.send(msg)
    },
    getWebSocket(){
        return window.ws;
    },
    getStatus() {
        if (ws.readyState == 0) {
            return "未连接";
        } else if (ws.readyState == 1) {
            return "已连接";
        } else if (ws.readyState == 2) {
            return "连接正在关闭";
        } else if (ws.readyState == 3) {
            return "连接已关闭";
        }
    },
    //关闭连接
    onCloseWs: function () {
        console.log('主动关闭连接！');
        //关闭websocket连接和关闭断开重连机制
        lockReconnect = true;
        // 调用 上面的websocket关闭方法
        window.ws.close();
    },

}

export default websocket;

//刷新闲置转卖相关————【location.reload();全局刷新，用户体验感不好】
function initDeal() {
    // location.reload();
    window.MyBuyDeal()
    window.MySaleDeal()
    window.AllDeal()
}



//根据消息标识做不同的处理
function messageHandle(message) {
    let msg = JSON.parse(message)
    // console.log(msg);
    switch (msg.type) {
        case 'init':
            console.log("连接成功，请求绑定");
            window.ws.send(JSON.stringify({type:"bind",token: window.sessionStorage.getItem('token')}));
            break;
        case 'bind':
            console.log("绑定成功",msg);
            break;
        case 'flush':
            console.log("需要刷新交易情况");
            initDeal();
            break;
        case 'inform':
            console.log("通知");
            break;
        default:
            console.log("未知消息类型");
    }
}

function reconnect() {
    if(lockReconnect) {
        return;
    }
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    websocket.Init();
    tt = setTimeout(function () {
        if(window.ws.readyState!=1)
        {
            console.log("执行断线重连...")
            console.log(websocket.getStatus())
            websocket.Init();
            lockReconnect = false;
        }
        else
        {
            clearTimeout(tt)
        }
    }, 4000);
}

// //心跳检测
// var heartCheck = {
//     timeout: 1000 * 60 * 3,
//     timeoutObj: null,
//     serverTimeoutObj: null,
//     start: function(){
//         console.log('开始心跳检测');
//         var self = this;
//         this.timeoutObj && clearTimeout(this.timeoutObj);
//         this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
//         this.timeoutObj = setTimeout(function(){
//             //这里发送一个心跳，后端收到后，返回一个心跳消息，
//             //onmessage拿到返回的心跳就说明连接正常
//             console.log('心跳检测...');
//             ws.send("HeartBeat:"+ clientId );
//             self.serverTimeoutObj = setTimeout(function() {
//                 if(ws.readyState!=1){
//                     ws.close();
//                 }
//                 // createWebSocket();
//             }, self.timeout);
//
//         }, this.timeout)
//     }
// }

